<template>
  <div class="appointments-list">
    <el-card shadow="never">
      <template #header>
        <div class="page-header">
          <h2>预约管理</h2>
          <el-button type="primary" @click="$router.push('/appointments/add')" v-if="authStore.userRole !== '用户'">
            <el-icon><Plus /></el-icon>
            添加预约
          </el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="queryForm" inline class="search-form">
        <el-form-item label="客户编号">
          <el-input v-model="queryForm.userId" placeholder="请输入客户编号" clearable />
        </el-form-item>
        <el-form-item label="宠物编号">
          <el-input v-model="queryForm.petId" placeholder="请输入宠物编号" clearable />
        </el-form-item>
        <el-form-item label="预约状态">
          <el-select v-model="queryForm.appointmentStatus" placeholder="请选择状态" clearable style="width: 200px;">
            <el-option label="新预约" value="新预约" />
            <el-option label="确认" value="确认" />
            <el-option label="进行中" value="进行中" />
            <el-option label="已完成" value="已完成" />
            <el-option label="取消" value="取消" />
            <el-option label="缺席" value="缺席" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="handleDateChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        style="width: 100%"
      >
        <el-table-column label="序号" width="80">
          <template #default="{ $index }">
            {{ (pagination.current - 1) * pagination.size + $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="userId" label="客户姓名" width="120" />
        <el-table-column prop="petId" label="宠物姓名" width="120" />
        <el-table-column prop="serviceId" label="服务项目" width="120" />
        <el-table-column prop="staffId" label="服务人员" width="120" />
        <el-table-column prop="resourceId" label="服务资源" width="120" />
        <el-table-column prop="startTime" label="开始时间" width="180" />
        <el-table-column prop="endTime" label="结束时间" width="180" />
        <el-table-column prop="appointmentStatus" label="预约状态" width="120" />
        <el-table-column label="操作" width="180" fixed="right" v-if="authStore.userRole !== '用户'">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { appointmentsApi } from '@/api'
import type { Appointments, AppointmentsQuery } from '@/types'
import { handlePageResponse } from '@/utils/pagination'

const router = useRouter()
const authStore = useAuthStore()

// 添加调试信息
console.log('AppointmentsList - authStore.userRole:', authStore.userRole)
console.log('AppointmentsList - authStore.user:', authStore.user)
console.log('AppointmentsList - authStore.user?.permissions:', authStore.user?.permissions)

// 查询表单
const queryForm = reactive<Omit<AppointmentsQuery, 'pageNum' | 'pageSize'>>({
  userId: undefined,
  petId: undefined,
  serviceId: undefined,
  staffId: undefined,
  appointmentStatus: ''
})

// 日期范围
const dateRange = ref<[string, string] | null>(null)

// 表格数据
const tableData = ref<Appointments[]>([])
const loading = ref(false)

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const params: any = {
      userId: queryForm.userId,
      petId: queryForm.petId,
      serviceId: queryForm.serviceId,
      staffId: queryForm.staffId,
      appointmentStatus: queryForm.appointmentStatus,
      pageNum: pagination.current,
      pageSize: pagination.size
    }
    // 处理时间范围
    if (dateRange.value && dateRange.value.length === 2) {
      params.startTime = dateRange.value[0]
      params.endTime = dateRange.value[1]
    }
    const response = await appointmentsApi.getPage(params)
    console.log('预约列表接口返回', response)
    const pageData = handlePageResponse<Appointments>(response)
    tableData.value = pageData.records
    pagination.total = pageData.total
  } catch (error) {
    console.error('获取预约列表失败:', error)
    ElMessage.error('获取预约列表失败')
  } finally {
    loading.value = false
  }
}

// 日期范围改变
const handleDateChange = (dates: [string, string] | null) => {
  dateRange.value = dates
  handleSearch() // 添加这行代码，当日期改变时自动触发搜索

}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

// 重置
const handleReset = () => {
  Object.assign(queryForm, {
    userId: undefined,
    petId: undefined,
    serviceId: undefined,
    staffId: undefined,
    appointmentStatus: ''
  })
  // 添加这行代码，重置日期范围
  dateRange.value = null
  pagination.current = 1
  fetchData()
}

// 添加
const handleAdd = () => {
  router.push('/appointments/add')
}

// 编辑
const handleEdit = (row: Appointments) => {
  router.push(`/appointments/update/${row.appointmentId}`)
}

// 删除
const handleDelete = async (row: Appointments) => {
  try {
    await ElMessageBox.confirm(`确定要删除预约记录吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await appointmentsApi.delete(row.appointmentId!.toString())
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    'PENDING': 'warning',
    'CONFIRMED': 'primary',
    'COMPLETED': 'success',
    'CANCELLED': 'danger',
    'IN_PROGRESS': 'info',
    'ABSENT': 'info'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'PENDING': '新预约',
    'CONFIRMED': '确认',
    'COMPLETED': '已完成',
    'CANCELLED': '取消',
    'IN_PROGRESS': '进行中',
    'ABSENT': '缺席'
  }
  return statusMap[status] || status
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  fetchData()
}

// 当前页改变
const handleCurrentChange = (current: number) => {
  pagination.current = current
  fetchData()
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.appointments-list {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 